package com.kalua.list.harvester.resultprocessing;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;
import com.kalua.list.domainmodel.NumericId;
import com.kalua.list.domainmodel.product.Product;
import com.kalua.list.harvester.parser.ProductParseResult;

public class FileBasedResultProcessor implements ResultProcessor {

	private static final Logger logger = 
			LoggerFactory.getLogger(FileBasedResultProcessor.class);	
	
	private File outputFile;
	private Map<NumericId,Product> toWrite;
	
	public FileBasedResultProcessor(File outputFile) {
		super();
		this.outputFile = outputFile;
		this.toWrite = Maps.newHashMap();
	}

	@Override
	public void accept(ProductParseResult results) {
		if (results.isConnectionFailed()) {
			logger.info(	"Ignoring results for {} as errors are not persisted.", 
								results.getVendorLinkProductId());
			return;
		}
		
		if (!results.isConnectionFailed()) {
			for (Product product : results.getProducts()) {
				this.toWrite.put(product.getId(),product);				
			}
		}
	}

	@Override
	public void writeCollectedResults() {
		logger.info("Writting {} records to JSON file.", this.toWrite.size());
		try (FileWriter writer = new FileWriter(this.outputFile)) {		
			ObjectMapper mapper = new ObjectMapper();
			mapper.writeValue(writer, this.toWrite);
		} catch (IOException exce) {
			logger.error("Failed to write results map to file.", exce);
		}
	}
}
